const router = require('koa-router')();
const cc = require('../conCtl');
const js = require('../jsCtl');
const db = require('../dbCtl');
const md5 = require('md5-node');

/**
@hostpath = http://127.0.0.1/service/login
 */


/** 后端登录
###
    POST {{hostpath}}/
    Content-Type: application/json

    {
        "uname":"tests",
        "pwd":"iiiiii",
        "verifycode":"aaaa"
    }
### */
router.post('/', async c => {
  js.check_params(
    !c.request.body.uname && '!用户名' ||
    !c.request.body.pwd && '!密码' ||
    !c.request.body.verifycode && '!验证码');

  if (c.request.body.verifycode != c.session.verifCode) js.throwObj('验证码错误', js.rescode.param_fail);

  let data = await db.model('`t_admin`').where('`account`=?', c.request.body.uname).shift('没有找到用户');
  let pwd = data['pwd'];
  if (md5(c.request.body.pwd) != pwd) js.throwObj('密码错误', js.rescode.param_fail);

  cc.auth_sess_init(c, data['id'], 2, data['account']);
  cc.send(c, {
    id: data['id'],
    account: data['account']
  });
});


const svgCaptcha = require('svg-captcha');
//生成验证码 返回图片格式
router.get('/', async c => {
  const codeConfig = {
    size: 4, // 验证码长度
    ignoreChars: '0oO1ilI', // 验证码字符中排除 0oO1ilI
    noise: 3, // 干扰线条的数量
    width: 120,
    height: 40,
    fontSize: 40,
    color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    background: '#eee',
  };
  const captcha = svgCaptcha.create(codeConfig);

  c.session.verifCode = captcha.text.toLowerCase(); // 存session用于验证接口获取文字码
  cc.send(c, captcha.data);
});

module.exports = router;